import { connect } from 'umi';
import { Spin, message } from 'antd';
import { useEffect, useState } from 'react';
import '../common/style.less';
import { DocumentControllerContext } from '../common/useOAContext';
import { DetailInfoTopViewOA } from './DetailInfoTopViewOA';
import { DetailInfoCenterViewOA } from './DetailInfoCenterViewOA';
import { DetailInfoBottomViewOA } from './DetailInfoBottomViewOA';
import { getPurchaseSourcePackServices, syncApplyStateService, syncPDFtoOAServices } from '../services/UpdateService';
import { getColorTextLoadMap, getPosIDs, getTenantID, getUserID, renderWaterMarkDom } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { GKZB, SHTG_CHECKSTATE, SHZ_CHECKSTATE, setOAMessageSev } from '../../Acommon';
import { BZWC_STATE, BZ_flowBusinessType, DBZ_STATE, WJBZZ_STATE } from '../common/Format';
import { RevokeModal } from '../../Acomponents/RevokeModal';

const DetailInfoViewOA: React.FC<Record<string, any>> = ({ locationProps, curRes }) => {
  const prefix = 'purchase-document-update-'; /** 样式根名称 */

  const [infoObj, setInfoObj] = useState<Record<string, any>>({}); /** 保存详情 */
  const [procureReal, setBusinessType] = useState<string>(GKZB()); /** 判断展示类型 */
  /**撤销弹窗*/
  const [invalidState, setInvalidState] = useState<Record<string, any>>({});
  const [radioState, setRadioState] = useState<Record<string, any>>({
    /** 表单Col控制显示和隐藏的状态 */ packFlag: 0,
    siteVisitFlag: 0,
    meetFlag: 0,
    sampleFlag: 0,
    productFlag: 0,
    charge: 0,
    unify: 0,
    sampleCheck: 0,
    supplyType: 1, // 项目属性  0 = 服务 1 = 货物
    bidMarginFlag: 0,
  });
  const [stateFlag, setStateFlag] = useState(false);

  // 初始化水印
  // useEffect(() => {
  //   renderWaterMarkDom('documentOAPage-divBox', true);
  //   return () => {
  //     renderWaterMarkDom('documentOAPage-divBox', false);
  //   };
  // }, []);

  /** 消息已读已办接口 */
  const { setOAMessageRun, setOAMessageLoaidng } = setOAMessageSev(() => {});

  /** 获取详情 */
  const { getPurchaseSourcePackRun, getPurchaseSourcePackLoading, reloadDetailInfo } = getPurchaseSourcePackServices((res: any) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      let { procureReal, procureRealName, state, checkState } = res?.obj;
      if (state == WJBZZ_STATE() && checkState == SHZ_CHECKSTATE()) {
        setStateFlag(true);
      }
      const { colorText } = getColorTextLoadMap(procureRealName);
      setInfoObj(res?.obj);
      if (res?.obj?.supplyType) {
        let radioList = { ...res?.obj };
        if (res?.obj?.supplyType == `${getTenantID()}${ILoadMapTypeAll?.PURCHASE_CATEGORY}1000`) {
          radioList.supplyType = 1;
        } else {
          radioList.supplyType = 0;
        }
        setRadioState(radioList); // 展示行控制
      }
      delete res?.obj?.['mpurchasePackList'];
      delete res?.obj?.['mpurchaseApply'];
      if (colorText) {
        setBusinessType(procureReal);
      }

      // 同步消息接口、做已读办理的接口处理
      let infoObject = res?.obj;
      if (infoObject && infoObject?.paramObject?.[BZ_flowBusinessType()]) {
        let workFlowNode = infoObject?.paramObject?.[BZ_flowBusinessType()];
        if (
          workFlowNode &&
          workFlowNode?.mactivitiTaskList?.length > 0 &&
          workFlowNode?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
          workFlowNode?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
        ) {
          setOAMessageRun({
            // 已读未办
            id: locationProps?.state?.taskId,
            isRemark: 0,
            viewType: 1,
          });
        }
      }
    }
  });

  /** 初始化 */
  useEffect(() => {
    if (locationProps?.state?.id) {
      getPurchaseSourcePackRun({ id: locationProps?.state?.id });
    }
  }, [locationProps?.state?.id]);

  /**同步申请【采购中】接口*/
  const { syncApplyStateRun, syncApplyStateLoading } = syncApplyStateService(() => {});

  const { syncPDFtoOARun, syncPDFtoOALoading } = syncPDFtoOAServices((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
    }
  });
  const syncPDFtoOARunfun = (infoObj) => {
    //需要调用同步接口
    let mactivitiHisTaskInstList =
      infoObj?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1003`]?.mactivitiHisProcinstList?.[0]?.mactivitiHisTaskInstList;
    let resObj = { ...infoObj, paramObject: { mactivitiHisTaskInstList } };
    syncPDFtoOARun(resObj);
  };

  useEffect(() => {
    if (infoObj?.state == BZWC_STATE() && infoObj?.checkState == SHTG_CHECKSTATE()) {
      if (stateFlag) {
        /**同步申请【采购中】接口*/
        syncApplyStateRun({ id: infoObj?.applyID, state: `${getTenantID()}${ILoadMapTypeAll?.PURAPPLY_STATE}1005` });
        syncPDFtoOARunfun(infoObj);
      }
    }
  }, [infoObj?.state, infoObj?.checkState]);

  return (
    <DocumentControllerContext.Provider
      value={{
        curRes,
        styleFixCls: prefix,
        infoObj,
        reloadDetail: reloadDetailInfo,
        procureReal,
        radioState,
        invalidState,
        setInvalidState,
        setOAMessageRun,
        taskId: locationProps?.state?.taskId,
      }}
    >
      <Spin spinning={getPurchaseSourcePackLoading || setOAMessageLoaidng || syncApplyStateLoading}>
        <div className={`${prefix}infoViewOA`} id={'documentOAPage-divBox'}>
          <DetailInfoTopViewOA />
          <DetailInfoCenterViewOA />
          <DetailInfoBottomViewOA />
        </div>
      </Spin>

      {invalidState?.isShow && (
        <RevokeModal
          resObj={invalidState?.resObj}
          revokeRequestUrl={'/purchaseSourceController/invalid'}
          onClose={() => setInvalidState({})}
          reqBody={{ state: DBZ_STATE() }}
          modalTip={
            <div style={{ color: '#000' }}>
              确认是否撤销【<span style={{ color: 'red' }}>{invalidState?.resObj?.packName}</span>】的审核, 撤销后可重新提交！
            </div>
          }
          reloadRequest={reloadDetailInfo}
        />
      )}
    </DocumentControllerContext.Provider>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(DetailInfoViewOA);
